package com.sixth.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sixth.core.entity.Menu;
import com.sixth.core.entity.RoleMenu;
import com.sixth.core.vo.R;
import com.sixth.core.util.WebUtil;
import com.sixth.system.mapper.MenuMapper;
import com.sixth.system.mapper.RoleMenuMapper;
import com.sixth.system.service.MenuService;
import com.sixth.system.vo.MenuVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;


@Service
public class MenuServiceImpl implements MenuService {
    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private RoleMenuMapper roleMenuMapper;
    @Override
    public R<List<Menu>> selectByUserId(Long userId) {
        List<Menu> menus = menuMapper.queryByUserId(userId);
        if(menus.size()==0){
            return R.error("用户没有权限");

        }
        return R.ok(menus);
    }

    @Override
    /**
     * 查询左侧菜单
     *
     * @return 返回封装了一级菜单及其子菜单的R对象
     */
    public R<List<Menu>> selectLeftMenu() {
        // 获取当前用户的名称
        String username = WebUtil.getUsername();
        // 根据用户名查询菜单
        List<Menu> menus = menuMapper.selectLeftMenu(username);
        // 封装菜单
        // 1. 得到一级菜单
        List<Menu> firstMenus = menus.stream().filter(menu -> menu.getParentId().equals(0L)).collect(Collectors.toList());
        // 2. 得到一级菜单对应的子菜单
        firstMenus.forEach(menu -> {
            // 得到一级菜单的id
            Long menuId = menu.getMenuId();
            // 根据一级菜单的id查询对应的子菜单
            List<Menu> children = menus.stream().filter(m -> m.getParentId().equals(menuId)).collect(Collectors.toList());
            // 设置子菜单
            menu.setChildren(children);
        });
        // 返回封装了一级菜单及其子菜单的R对象
        return R.ok(firstMenus);
    }

    @Override
    public R<List<Menu>> selectAll(MenuVo menuVo) {
        QueryWrapper<Menu> wrapper = new QueryWrapper<>();
        if (menuVo.getMenuName()!=null){
            wrapper.like("menu_name",menuVo.getMenuName());
        }
        if (menuVo.getStatus()!=null){
            wrapper.eq("status",menuVo.getStatus());
        }
        List<Menu> menus = menuMapper.selectList(wrapper);
        return R.ok(menus);
    }

    @Override
    public R<Menu> getMenuById(Long menuId) {
        Menu menu = menuMapper.selectById(menuId);
        return R.ok(menu);
    }

    @Override
    public boolean add_update_menu(Menu menu) {
        return menuMapper.insertOrUpdate(menu);
    }

    @Override
    public R<List<Menu>> selectMenusByRoleId(Long roleId) {
        List<Menu> menus = menuMapper.selectMenusByRoleId(roleId);
        if(menus.size() == 0){
            return R.error("用户没有权限");
        }
        return R.ok(menus);
    }
    //保存角色和菜单之间的关系
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R saveRoleMenu(Long roleId, Long[] finalKey) {
        if (roleId == null) {
            return R.error("角色ID不能为空");
        }

        try {
            // 删除该角色的所有现有菜单关联
            QueryWrapper<RoleMenu> wrapper = new QueryWrapper<>();
            wrapper.eq("role_id", roleId);
            roleMenuMapper.delete(wrapper);

            // 如果 finalKey 为空或长度为0，表示清空所有权限
            if (finalKey == null || finalKey.length == 0) {
                return R.ok("所有权限已清空");
            }

            // 批量插入新的角色-菜单关联
            List<RoleMenu> roleMenuList = Arrays.stream(finalKey)
                    .map(menuId -> new RoleMenu(roleId, menuId))
                    .collect(Collectors.toList());

            for (RoleMenu roleMenu : roleMenuList) {
                roleMenuMapper.insert(roleMenu);
            }

            return R.ok("角色菜单关联保存成功");
        } catch (Exception e) {
            throw new RuntimeException("保存角色菜单关联失败", e);
        }
    }


    @Override
    public R<List<Menu>> listAllMenu() {
        QueryWrapper<Menu> wrapper = new QueryWrapper<>();
        wrapper.eq("status",0);
        List<Menu> menus = menuMapper.selectList(wrapper);
        return R.ok(menus);
    }

    @Override
    public R removeById(Long menuId) {
        return R.ok(menuMapper.deleteById(menuId));
    }

}